#include <iostream>

using namespace std;

class Solution {
private:
    string* s;
    string helper(int &index) {
        string back;
        string buff;
        index++;
        for (; index < s->length(); index++) {
            if (s->at(index) == '(') {
                buff += helper(index);
            } else if (s->at(index) == ')') {
                break;
            } else {
                buff += s->at(index);
            }
        }
        for (int i = buff.length() - 1; i >= 0; i--) {
            back += buff[i];
        }
        return back;
    }
public:
    string reverseParentheses(string s) {
        this->s = &s;
        string output;
        int index;
        for (index = 0; index < s.length(); index++) {
            if (s[index] == '(') {
                output += helper(index);
            } else if (s[index] != ')') {
                output += s[index];
            }
        }
        return output;
    }
};


int main() {
    Solution solution;
    string input = "a(bcdefghijkl(mno)p)q";
    string out = solution.reverseParentheses(input);
    cout << out << endl;
}